package com.moorecat.app;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.moorecat.MooerApplication;
import com.moorecat.R;
import com.moorecat.http.HttpUtils;
import com.moorecat.utils.UtilTools;
import com.moorecat.utils.ui.ProgressLinearLayout;

/**
 * @author pengfei.xu
 * @version 创建时间：2011-6-12 上午07:49:38 类说明
 */
public class BusinessComment extends Activity implements OnClickListener {

	private static final String TAG = "BusinessComment";

	private ImageView remark;

	private ListView listView;

	private CommentAdapter adapter;

	private ProgressLinearLayout footer;

	private List<com.moorecat.bean.Comment> list = new ArrayList<com.moorecat.bean.Comment>();

	private int shopId;

	private MooerApplication mooerApp;

	private long taskId;

	private List<Integer> selectedItems = new ArrayList<Integer>();
	
	private boolean isCancelled;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.business_comment);
		mooerApp = (MooerApplication) getApplication();
		Intent intent = getIntent();
		shopId = intent.getIntExtra("shopId", 0);
		remark = (ImageView) findViewById(R.id.remark);
		listView = (ListView) findViewById(R.id.listview);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);
		adapter = new CommentAdapter();
		listView.setAdapter(adapter);

		remark.setOnClickListener(this);
		footer.setOnClickListener(this);

		new CommentTask().execute(shopId);
	}

	@Override
	public void onClick(View v) {
		if (v == remark) {
			if (mooerApp.isLoggedin()) {
				Intent intent = new Intent(this, Comment.class);
				intent.putExtra("shopId", shopId);
				startActivityForResult(intent, 0);
			} else {
				Intent intent = new Intent(this, MoreAccountSetting.class);
				intent.putExtra("isFinish", true);
				startActivityForResult(intent, 0);
			}
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "on activity result");
		if (data != null) {
			com.moorecat.bean.Comment comment = (com.moorecat.bean.Comment) data
					.getSerializableExtra("comment");
			if (comment != null) {
				if (list.size() == 0) {
					try {
						listView.removeFooterView(footer);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				list.add(comment);
				adapter.notifyDataSetChanged();
			}
		}

		// listView.addFooterView(footer);
		// new CommentTask().execute(shopId);
	}

	public class CommentAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			com.moorecat.bean.Comment com = list.get(position);
			LinearLayout itemView = (LinearLayout) LayoutInflater.from(
					BusinessComment.this).inflate(
					R.layout.business_comment_item, null);
			ImageView pic = (ImageView) itemView.findViewById(R.id.pic);
			final TextView content = (TextView) itemView
					.findViewById(R.id.comment_content);
			final TextView more = (TextView) itemView.findViewById(R.id.more);
			TextView name = (TextView) itemView.findViewById(R.id.name);
			TextView num = (TextView) itemView.findViewById(R.id.xiaofei_num);
			TextView avg = (TextView) itemView.findViewById(R.id.xiaofe_avg);
			TextView taste = (TextView) itemView.findViewById(R.id.kouwei);
			TextView env = (TextView) itemView.findViewById(R.id.huanjing);
			TextView service = (TextView) itemView.findViewById(R.id.fuwu);
			TextView commentTitle = (TextView) itemView
					.findViewById(R.id.comment_title);
			final TextView commentContent = (TextView) itemView
					.findViewById(R.id.comment_content);
			TextView time = (TextView) itemView.findViewById(R.id.time);
			ImageView star = (ImageView) itemView.findViewById(R.id.star);
			name.setText(com.getUser().getUserName());
			num.setText(getString(R.string.xiaofei_num, com.getPeople()));
			avg.setText(getString(R.string.zifei_avg, com.getCost()));
			taste.setText(UtilTools.convertRating(com.getRating_taste()));
			env.setText(UtilTools.convertRating(com.getRating_env()));
			service.setText(UtilTools.convertRating(com.getRating_service()));
			if (com.getTitle() == null || "".equals(com.getTitle())) {
//				commentTitle.getLayoutParams().height=5;
				commentTitle.setVisibility(View.GONE);
			} else {
				commentTitle.setText(com.getTitle());
			}
			commentContent.setText(com.getContent());
			time.setText(com.getDate());
			pic.setImageBitmap(com.getUser().getIcon());
			if (commentContent.getText().length() > 54) {
				more.setVisibility(View.VISIBLE);
			} else {
				more.setVisibility(View.GONE);
			}
			if (selectedItems.contains(position)) {
				content.setMaxLines(100);
				more.setVisibility(View.GONE);
			}
			itemView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View paramView) {
					if (commentContent.getText().length() > 54) {
						if (selectedItems.contains(position)) {
							content.setMaxLines(3);
							more.setVisibility(View.VISIBLE);
							selectedItems.remove((Integer) position);
						} else {
							content.setMaxLines(100);
							more.setVisibility(View.GONE);
							selectedItems.add(position);
						}
					}
				}
			});
			return itemView;
		}

	}

	private class CommentTask extends
			AsyncTask<Integer, Integer, List<com.moorecat.bean.Comment>> {

		private boolean isException;

		@Override
		protected List<com.moorecat.bean.Comment> doInBackground(
				Integer... params) {
			List<com.moorecat.bean.Comment> list = null;
			try {
				list = HttpUtils.fetchShopCommentList(params[0], 0, 100);
				for (com.moorecat.bean.Comment comment : list) {
					comment.getUser().setIcon(mooerApp.getAvatarIcon());
				}
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<com.moorecat.bean.Comment> result) {
			super.onPostExecute(result);
			if (isException) {
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					list.addAll(result);
					listView.removeFooterView(footer);
					adapter.notifyDataSetChanged();
					new BitmapTask().execute("");
				} else {
					footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
							View.GONE);
					footer.setText(null, "暂无评论");
				}
			}

		}

	}

	private class BitmapTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			long id = System.currentTimeMillis();
			taskId = id;
			// 增加一个缓存List避免列表长度变化时遍历发生错误
			List<com.moorecat.bean.Comment> cacheList = new ArrayList<com.moorecat.bean.Comment>();
			cacheList.addAll(list);
			Iterator<com.moorecat.bean.Comment> it = cacheList.iterator();
			while (it.hasNext()) {
				/*
				 * 避免重复下载,如果有新的线程,则停止老的线程
				 */
				if (id != taskId||isCancelled) {
					break;
				}
				com.moorecat.bean.Comment comment = it.next();
				Bitmap icon = null;
				try {
					if (comment.getUser().getIcon() == mooerApp.getAvatarIcon()) {
						icon = HttpUtils.downloadBitmap(comment.getUser()
								.getPhoto());
						if (icon != null) {
							comment.getUser().setIcon(icon);
							publishProgress(0);
						}
					}
				} catch (Exception e) {

				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			adapter.notifyDataSetChanged();
		}

	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		isCancelled = true;
	}

}
